import BaseComponent from 'src/common/components/common/BaseComponent';
import { Pagination } from 'antd';
import { IExtendedPagationConfig } from 'src/models/common/common';
import React from 'react';

type IProps = IExtendedPagationConfig<{ immediately?: boolean, onChange?: (current:number, pageSize:number) => any, total?: number }>

type Istate = IExtendedPagationConfig

class PaginationTable extends BaseComponent<IProps, Istate> {
  public state = {
    current: this.props.defaultCurrent || this.props.current || 1,
    pageSize: this.props.defaultPageSize ||this.props.pageSize || 20,
  }

  public componentDidMount () {
    if (this.props.immediately) {
      this.handleChange()
    }
  }

  public render() {
    return (
      <div className={this.props.className || ''} style={this.props.style || {}}>
        {this.props.children}
        <div style={{ textAlign: 'right', padding: 15, background: 'white' }} >
          <Pagination
            showSizeChanger={true}
            showQuickJumper={true}
            defaultPageSize={this.state.pageSize}
            defaultCurrent={this.state.current}
            current={this.state.current}
            total={this.props.total}
            onShowSizeChange={(_, pageSize) => {
              this.setState({ current: 1, pageSize });
              this.handleChange();
            }}
            onChange={(current, pageSize) => {
              this.setState({ current, pageSize });
              this.handleChange();
            }}
          />
        </div>
      </div>
    )
  }

  private handleChange() {
    if (this.props.onChange) {
      Promise.resolve().then(() => this.props.onChange && this.props.onChange(this.state.current, this.state.pageSize));
    }
  }
}

export default PaginationTable